﻿function PositionViewModel(parent) {
    var self = this;

    // knockout variables
    self.positions = ko.observableArray([]);
    self.myPositions = ko.observableArray([]);
    self.workingPosition = ko.observable(null);
    self.workingPositionId = ko.observable(null);
    self.workingPositionBuffer = ko.observable(new Position({ }));
    self.positionAdvancedSearch = ko.observable(new PositionAdvancedSearch({ ContractType: "" }));
    self.positionViewMode = ko.observable("list");
    self.listPositionViewMode = ko.observable(true);
    self.detailsPositionViewMode = ko.observable(false);
    self.editPositionViewMode = ko.observable(false);
    self.selectedCountryId = ko.observable(-1);
    self.selectedIndustryId = ko.observable(-1);
    self.selectedCategoryId = ko.observable(-1);
    self.selectedSubcategoryId = ko.observable(-1);
    self.selectedJobType = ko.observable(-1);
    self.pageSize = ko.observable();
    self.countryTags = ko.observableArray([]);
    self.industryTags = ko.observableArray([]);
    self.categoryTags = ko.observableArray([]);
    self.technologyTags = ko.observableArray([]);
    self.companyTags = ko.observableArray([]);
    self.keywordTags = ko.observableArray([]);
    self.employmentTypeTags = ko.observableArray([]);
    self.keyword = ko.observable("");
    self.enterKeyPressed = false;
    self.advancedSearchPositionViewMode = ko.observable(false);


    //JOB TYPES
    self.jobTypes = ko.observableArray([]);
    self.jobTypesDecode = ko.computed(function() {
        var list = new Array();
        if (self.workingPosition()) {
            for (var i = 0; i < parent.profile.availableJobTypes().length; i++) {
                if ((parent.profile.availableJobTypes()[i].Value & self.workingPosition().JobType()) > 0) {
                    list.push(parent.profile.availableJobTypes()[i]);
                }
            }
        }
        self.jobTypes(list);
    });
    self.excludedJobTypes = ko.observableArray([]);
    self.excludeJobTypes = ko.computed(function() {
        // if workingPosition changes and it is not null
        if (self.workingPosition()) {
            var newArray = new Array();
            // go through all available employment types and select those that aren't inlcuded
            for (i in parent.profile.availableJobTypes()) {
                var found = false;
                var availableJobType = parent.profile.availableJobTypes()[i];
                for (j in self.jobTypes()) {
                    var selectedJobType = self.jobTypes()[j];
                    if (availableJobType.Value == selectedJobType.Value) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    newArray.push(availableJobType);
                }
            }
            self.excludedJobTypes(newArray);
        }

    });
    self.addJobType = function(employment) {
        var array = [];
        if (employment.Value == 0) {
            for (var i = 0; i < parent.profile.availableJobTypes().length; i++) {
                if (parent.profile.availableJobTypes()[i].Value != 0) {
                    array.push(parent.profile.availableJobTypes()[i]);
                }
            }
            self.jobTypes(array);
        } else {
            self.jobTypes.push(employment);
        }
    };
    self.removeJobType = function(employment) {
        self.jobTypes.remove(employment);
    };

    self.allJobTypesBtnVisible = ko.computed(function() {
        if (self.workingPosition()) {
            if (self.excludedJobTypes().length > 1) {
                return true;
            }
            return false;
        }
        return false;
    });

    //RESET TAGS LISTS
    self.resetTagsLists = function() {
        self.countryTags([]);
        self.industryTags([]);
        self.categoryTags([]);
        self.technologyTags([]);
        self.companyTags([]);
        self.keywordTags([]);
    };

    self.inspectViewMode = ko.computed(function() {
        var mode = self.positionViewMode();
        if (mode == "list") {
            self.listPositionViewMode(true);
            self.detailsPositionViewMode(false);
            self.editPositionViewMode(false);
            self.advancedSearchPositionViewMode(false);
        } else if (mode == "myList") {
            self.listPositionViewMode(true);
            self.detailsPositionViewMode(false);
            self.editPositionViewMode(false);
            self.advancedSearchPositionViewMode(false);
        } else if (mode == "details") {
            self.listPositionViewMode(false);
            self.detailsPositionViewMode(true);
            self.editPositionViewMode(false);
            self.advancedSearchPositionViewMode(false);
        } else if (mode == "edit") {
            self.listPositionViewMode(false);
            self.detailsPositionViewMode(false);
            self.editPositionViewMode(true);
            self.advancedSearchPositionViewMode(false);
        } else if (mode == "advancedSearch") {
            self.listPositionViewMode(false);
            self.detailsPositionViewMode(false);
            self.editPositionViewMode(false);
            self.advancedSearchPositionViewMode(true);
        }

    });
    self.selectPosition = function(position) {
        self.workingPosition(position);
    };
    self.deselectPosition = function() {
        self.workingPosition(null);
    };
    self.select = function(position) {
        self.selectposition(position);
    };
    //self.createMode = ko.observable(false);
    self.selectNew = function() {
        var newPosition = new Position({ });
        self.myPositions.push(newPosition);
        self.selectPosition(newPosition);
        self.workingPositionId(self.workingPosition().Id());
        self.gmapLocationEditMode();
        self.positionViewMode("edit");
        self.generateRoute();
    };

    self.selectDetails = function(position) {
        self.selectPosition(position);
        var loc = self.workingPosition() ? self.workingPosition().Location() ? self.workingPosition().Location() : "" : "";
        $.when(loadGoogleMaps(3, null, null))
            .then(function() {
                $.cachedScript("../../Scripts/gmap3/gmap3.min.js").done(function() {
                    $("#locationPositionViewMode").gmap3({
                            action: 'getAddress',
                            address: loc,
                            callback: function(results) {
                                if (!results) return;
                                $("#locationPositionViewMode").gmap3(
                                    { action: 'clear', name: 'marker' },
                                    { action: 'addMarker', latLng: results[0].geometry.location },
                                    { action: 'setCenter', args: [results[0].geometry.location] }
                        );
                            }
                        });
                });
            });
        self.workingPositionId(self.workingPosition().Id());
        self.positionViewMode("details");
        self.generateRoute();
    };

    self.selectEdit = function(position) {
        self.selectPosition(position);
        self.gmapLocationEditMode();
        self.workingPositionId(self.workingPosition().Id());
        self.positionViewMode("edit");
        self.generateRoute();
    };

    //SIMPLE SEARCH
    self.simpleSearch = function() {
        self.positionAdvancedSearch().CountryIds([]);
        self.positionAdvancedSearch().CountryIds().push(self.selectedCountryId());
        self.generateRoute();
    };

    self.resetAdvancedSearch = function() {
        self.positionAdvancedSearch(new PositionAdvancedSearch({ }));
        self.keywordTags([]);
        self.countryTags([]);
        self.industryTags([]);
        self.categoryTags([]);
        self.technologyTags([]);
        self.companyTags([]);
        self.employmentTypeTags([]);
    };

    //CENTER MODALS
    self.initAdvancedSearchPositionModal = function() {
        $('#AdvancedSearchPosition').on('shown', function() {
            var modal;
            modal = $(this);
            modal.css('margin-top', (modal.outerHeight() / 2) * -1).css('margin-left', (modal.outerWidth() / 2) * -1);
            return this;
        });
    };

    //CATEGORIES
    self.selectCatVisible = ko.observable(true);
    self.selectCatNotVisible = ko.observable(false);
    self.availableCategories = ko.observableArray([]);
    self.breadCrumbCategories = ko.observableArray([{ Id: -1, Description: "Start" }]);
    self.getChildCategories = function(category) {
        $.getJSON('/ExpertProfile/GetChildCategories', category, function(result) {
            self.availableCategories(result);
        });
    };
    self.resetCategories = function() {
        self.getChildCategories(null);
        self.breadCrumbCategories([{ Id: -1, Description: "Start" }]);
    };
    self.selectBreadCrumbCategory = function(category) {
        var index = 0;
        var count = self.breadCrumbCategories().length;

        // find the index of the selected bread crumb category
        for (; index < count; index++) {
            if (self.breadCrumbCategories()[index].Id == category.Id) {
                break;
            }
        }
        var deleteCount = count - index - 1;
        //returns the selected category
        if (deleteCount > 0) {
            self.breadCrumbCategories.splice(index + 1, deleteCount);
        }
        self.getChildCategories(category);
    };

    self.addCategory = function(category) {
        if (category.IsLeaf) {
            var foundCategory = ko.utils.arrayFirst(self.workingPositionBuffer().Categories(), function(item) {
                return item.Id == category.Id;
            });
            if (!foundCategory) {
                self.workingPositionBuffer().Categories.push(category);
                self.selectCatVisible(false);
                self.selectCatNotVisible(true);
            }
        } else {
            self.breadCrumbCategories.push(category);
            self.getChildCategories(category);
        }
    };

    self.removeCategory = function(category) {
        self.workingPositionBuffer().Categories.remove(category);
    };

    //EDIT MODE- EDIT Position
    self.selectTitle = function() {
        self.workingPositionBuffer().Title(self.workingPosition().Title());
    };
    self.okTitle = function() {
        if (self.workingPositionBuffer().Title.isValid()) {
            self.workingPosition().Title(self.workingPositionBuffer().Title());
            $("#TitlePositionDialog1").modal("hide");
        }
    };
    self.cancelTitle = function() {
        $("#TitlePositionDialog").modal("hide");
    };
    self.selectDescription = function() {
        self.workingPositionBuffer().Description(self.workingPosition().Description());
    };
    self.okDescription = function() {
        if (self.workingPositionBuffer().Description.isValid()) {
            self.workingPosition().Description(self.workingPositionBuffer().Description());
            $("#DescriptionPositionDialog").modal("hide");
        }
    };
    self.cancelDescription = function() {
        $("#DescriptionPositionDialog").modal("hide");
    };
    self.selectLocation = function() {
        self.workingPositionBuffer().Location(self.workingPosition().Location());
        var loc = self.workingPosition() ? self.workingPosition().Location() ? self.workingPosition().Location() : "" : "";
        $.when(loadGoogleMaps(3, null, null))
            .then(function() {
                $.cachedScript("../../Scripts/gmap3/gmap3.min.js").done(function() {
                    $("#locationPosition").gmap3({
                            action: 'getAddress',
                            address: loc,
                            callback: function(results) {
                                if (!results) return;
                                $("#locationPosition").gmap3(
                                    { action: 'clear', name: 'marker' },
                                    { action: 'addMarker', latLng: results[0].geometry.location },
                                    { action: 'setCenter', args: [results[0].geometry.location] },
                                    { action: 'clear', name: 'InfoWindow' },
                                    {
                                        action: 'addInfoWindow',
                                        address: loc,
                                        map: {
                                            center: true,
                                            zoom: 10
                                        },
                                        infowindow: {
                                            options: { content: loc }
                                        }
                                    }
                );
                            }
                        });
                });
            });
        self.gmapLocationAutocomplete();
    };
    self.okLocation = function() {
        var location = $("#locationAutocompletePosition").val();
        self.workingPosition().Location(location);
        $("#LocationPositionDialog").modal("hide");
    };
    self.cancelLocation = function() {
        $("#LocationPositionDialog").modal("hide");
    };
    self.selectJobType = function() {
        self.workingPositionBuffer().JobType(self.workingPosition().JobType());
    };
    self.okJobType = function() {
        var result;
        if (self.jobTypes().length == 0) {
            result = 0;
        } else {
            result = self.jobTypes()[0].Value;
            for (var i = 1; i < self.jobTypes().length; i++) {
                result = result | self.jobTypes()[i].Value;
            }
        }
        self.workingPosition().JobType(result);
        $("#JobTypePositionDialog").modal("hide");
    };
    self.cancelJobType = function() {
        $("#JobTypePositionDialog").modal("hide");
    };
    self.selectDuration = function() {
        self.workingPositionBuffer().Duration(self.workingPosition().Duration());
    };
    self.okDuration = function() {
        if (self.workingPositionBuffer().Duration.isValid()) {
            self.workingPosition().Duration(self.workingPositionBuffer().Duration());
            $("#DurationPositionDialog").modal("hide");
        }
    };
    self.cancelDuration = function() {
        $("#DurationPositionDialog").modal("hide");
    };
    self.selectStartDate = function() {
        self.workingPositionBuffer().StartDate(self.workingPosition().StartDate());
    };
    self.okStartDate = function() {
        if (self.workingPositionBuffer().StartDate.isValid()) {
            self.workingPosition().StartDate(self.workingPositionBuffer().StartDate());
            $("#StartDatePositionDialog").modal("hide");
        }
    };
    self.cancelStartDate = function() {
        $("#StartDatePositionDialog").modal("hide");
    };
    self.selectCountry = function() {
        //for update mode
        if (self.workingPosition().Id() != 0) {
            var country = $.Enumerable.From(parent.availableCountries()).SingleOrDefault(null, function(x) {
                return self.workingPosition().Country().Id === x.Id;
            });
            if (country != null) {
                self.workingPositionBuffer().Country(country);
            }
            $("#CountryUpdatePositionDialog").modal("show");
        }
            //for create new mode
        else {
            $("#CountryPositionDialog").modal("show");
        }
    };
    self.okCountry = function() {
        if (self.workingPositionBuffer().Country.isValid()) {
            self.workingPosition().Country(self.workingPositionBuffer().Country());
            //for update mode
            if (self.workingPosition().Id() != 0) {
                $("#CountryUpdatePositionDialog").modal("hide");
            } else {
                $("#CountryPositionDialog").modal("hide");
            }
        }
    };
    self.cancelCountry = function() {
        if (self.workingPosition().Id() != 0) {
            $("#CountryUpdatePositionDialog").modal("hide");
        } else {
            $("#CountryUPositionDialog").modal("hide");
        }
    };
    self.selectCategories = function() {
        self.getChildCategories();
        self.workingPositionBuffer().Categories(self.workingPosition().Categories());
    };
    self.okCategories = function() {
        self.workingPosition().Categories(self.workingPositionBuffer().Categories());
        self.resetCategories();
        $("#CategoriesPositionDialog").modal("hide");
    };
    self.cancelCategories = function() {
        self.resetCategories();
        $("#CategoriesPositionDialog").modal("hide");
    };
    self.selectTechnologies = function() {
        self.loadTechnologies();
        self.workingPositionBuffer().Technologies(self.workingPosition().Technologies());
    };
    self.okTechnologies = function() {
        self.workingPosition().Technologies(self.workingPositionBuffer().Technologies());
        $("#TechnologiesPositionDialog").modal("hide");
    };
    self.cancelTechnologies = function() {
        $("#TechnologiesPositionDialog").modal("hide");
    };
    self.selectIndustry = function() {
        //for update mode
        if (self.workingPosition().Id() != 0) {
            var industry = $.Enumerable.From(parent.availableIndustriesWithoutAll()).SingleOrDefault(null, function(x) {
                return self.workingPosition().Industry().Id === x.Id;
            });
            if (industry != null) {
                self.workingPositionBuffer().Industry(industry);
            }
            $("#IndustryUpdatePositionDialog").modal("show");
        }
            //for create new mode
        else {
            $("#IndustryPositionDialog").modal("show");
        }
    };
    self.okIndustry = function() {
        if (self.workingPositionBuffer().Industry.isValid()) {
            self.workingPosition().Industry(self.workingPositionBuffer().Industry());
            //for update mode
            if (self.workingPosition().Id() != 0) {
                $("#IndustryUpdatePositionDialog").modal("hide");
            } else {
                $("#IndustryPositionDialog").modal("hide");
            }
        }
    };
    self.cancelIndustry = function() {
        if (self.workingPosition().Id() != 0) {
            $("#IndustryUpdatePositionDialog").modal("hide");
        } else {
            $("#IndustryPositionDialog").modal("hide");
        }
    };
    self.okPhoto = function() {
        if (self.workingPositionBuffer().Photo.isValid()) {
            self.workingPosition().Photo(self.workingPositionBuffer().Photo());
            self.resetPhotoUpload();
            $("#PhotoPositionDialog").modal("hide");
        }
    };
    self.cancelPhoto = function() {
        self.resetPhotoUpload();
        $("#PhotoPositionDialog").modal("hide");
    };
    self.checkPhoto = ko.computed(function() {
        if (self.workingPosition()) {
            var photo = self.workingPosition().Photo();
            self.workingPosition().Photo150X150(photo.replace("/250X250_", "/150X150_"));
            self.workingPosition().Photo80X80(photo.replace("/250X250_", "/80X80_"));
        }
    });


    //LOCATION VISIBILITY
    self.locationVisible = ko.observable(false);
    self.locationMapVisible = ko.observable(false);
    self.isLocationVisible = ko.computed(function() {
        if (self.workingPosition() != null) {
            if (self.workingPosition().Country() != null) {
                self.locationVisible(true);
                if (self.workingPosition().Location() != "") {
                    self.locationMapVisible(true);
                } else {
                    self.locationMapVisible(false);
                }
            } else {
                self.locationVisible(false);
            }
        }
    });

    // CATEGORIES/TECHNOLOGIES VISIBILITY
    self.categoriesTechnologiesVisible = ko.observable(false);
    self.areCategoriesTechnologiesVisible = ko.computed(function() {
        if (self.workingPosition()) {
            if (self.workingPosition().Industry() != null) {
                self.categoriesTechnologiesVisible(true);
            }
        }
    });

    // NAME/DESCRIPTION LABELS VISIBILITY
    self.nameVisible = ko.observable(true);
    self.isNameVisible = ko.computed(function() {
        if (self.workingPosition() != null) {
            if (self.workingPosition().Title() != null && self.workingPosition().Title() != "") {
                self.nameVisible(false);
            }
        }
    });
    self.descriptionVisible = ko.observable(true);
    self.isDescriptionVisible = ko.computed(function() {
        if (self.workingPosition() != null) {
            if (self.workingPosition().Description() != null && self.workingPosition().Description() != "") {
                self.descriptionVisible(false);
            }
        }
    });

    //CRUD OPERATIONS
    self.alertVisible = ko.observable(false);
    self.tableOfPositionsVisible = ko.observable(false);
    self.youAreNotAllowedAlertVisible = ko.observable(true);
    self.SaveOrUpdate = function() {
        if (self.workingPosition().Id() == 0) {
            $.ajax({
                    url: "/Position/Save",
                    type: 'post',
                    data: ko.toJSON(self.workingPosition()),
                    contentType: 'application/json',
                    success: function(id) {
                        self.workingPosition().Id(id);
                        self.selectDetails(self.workingPosition());
                    }
                });
        } else {
            self.alertVisible(true);
        }
        $.ajax({
                url: "/Position/Update",
                type: 'post',
                data: ko.toJSON(self.workingPosition()),
                contentType: 'application/json',
                success: function(result) {
                    if (result != "ERROR") {
                        self.selectDetails(self.workingPosition());
                    } else {
                        self.tableOfPositionsVisible(false);
                        self.youAreNotAllowedAlertVisible(true);
                    }
                }
            });
    };

    self.deletePosition = function() {
        $.ajax({
                url: "/Position/DeletePosition",
                type: 'post',
                data: ko.toJSON(self.workingPosition()),
                contentType: 'application/json',
                success: function() {
                    self.Positions.remove(function(item) { return item.Id() == self.workingPosition().Id(); });
                    if (self.PositionViewMode() == "details") {
                        self.PositionViewMode("myList");
                    }
                    $('#DeletePositionDialog').modal('hide');
                }
            });
    };

    self.cancelDeletePosition = function() {
        self.deselectPosition();
        $('#DeletePositionDialog').modal('hide');

    };

    //TECHNOLOGIES
    self.technologyName = ko.observable("");
    self.createAndAddTechnology = function() {
        var newTech = $("#TechnologiesPositionEditMode").val();
        self.technologyName(newTech);
        $.getJSON("/Position/CreateTechnology", { technologyName: self.technologyName(), industryId: self.workingPosition().Industry().Id }, function(technologyArray) {
            var mappedTechnologies = $.map(technologyArray, function(item) { return new Technology(item); });
            for (var i = 0; i < mappedTechnologies.length; i++) {
                self.workingPositionBuffer().Technologies.push(mappedTechnologies[i]);
            }
            $("#TechnologiesPositionEditMode").val("");
        });
    };
    self.removeTechnology = function(technology) {
        self.workingPositionBuffer().Technologies.remove(technology);
    };
    self.autocompleteTechnologiesEditMode = function() {
        $("#TechnologiesPositionEditMode").autocomplete({
                source: function(request, response) {
                    $.ajax({
                            url: "Technology/GetTechnologiesAutocomplete",
                            dataType: "json",
                            data: {
                                searchTerm: request.term,
                                maxRows: 8
                            },
                            success: function(data) {
                                response($.map(data, function(item) {
                                    return {
                                        label: item.Name,
                                        value: item.Name
                                    };
                                }));
                            }
                        });
                },
                minLength: 0,
                focus: function(event, ui) {
                    this.value = ui.item.label;
                    event.preventDefault(); // Prevent the default focus behavior.
                }
            });
    };

    //PAGING
    self.pagesCount = ko.observable(1);
    self.count = ko.observable(0);
    self.lastPage = function() {
        self.positionAdvancedSearch().PageIndex(self.pagesCount() - 1);
        self.generateRoute();
    };
    self.firstPage = function() {
        self.positionAdvancedSearch().PageIndex(0);
        self.generateRoute();
    };
    self.nextPage = function() {
        if (self.positionAdvancedSearch().PageIndex() < self.pagesCount() - 1) {
            self.positionAdvancedSearch().PageIndex(self.positionAdvancedSearch().PageIndex() + 1);
        }
        self.generateRoute();
    };
    self.previousPage = function() {
        if (self.positionAdvancedSearch().PageIndex() > 0) {
            self.positionAdvancedSearch().PageIndex(self.positionAdvancedSearch().PageIndex()() - 1);
        }
        self.generateRoute();
    };
    self.pageNumber = function(number) {
        self.positionAdvancedSearch().PageIndex(number);
        self.generateRoute();
    };
    self.fromPageNumber = ko.computed(function() {
        return (self.positionAdvancedSearch().PageSize() * (self.positionAdvancedSearch().PageIndex() + 1)) - self.positionAdvancedSearch().PageSize() + 1;
    });
    self.toPageNumber = ko.computed(function() {
        return self.positionAdvancedSearch().PageSize() * (self.positionAdvancedSearch().PageIndex() + 1);
    });

    self.pageSize = ko.observable(3);
    self.pageSize.subscribe(function(newValue) {
        self.positionAdvancedSearch().PageSize(newValue);
        if (parent.route() == "Positions") {
            self.generateRoute();
        }

    });
    //SET INDUSTRYID
    self.industryId = ko.observable(0);
    self.setIndustryId = function(industry) {
        self.positionAdvancedSearch().IndustryIds().push(industry.Id);
        self.selectedIndustryId(industry.Id);
        self.generateRoute();
    };
    //SET COUNTRYID
    self.countryId = ko.observable(0);
    self.setCountryId = function(position) {
        self.positionAdvancedSearch().CountryIds().push(position.CountryId());
        self.selectedCountryId(position.CountryId());
        self.generateRoute();
    };
    //SET CATEGORYID
    self.categoryId = ko.observable(0);
    self.setCategoryId = function(category) {
        self.positionAdvancedSearch().CategoryIds().push(category.Id);
        self.selectedSubcategoryId(category.Id);
        self.generateRoute();
    };
    //SET TECHNOLOGYID
    self.technologyId = ko.observable(0);
    self.setTechnologyId = function(technology) {
        self.positionAdvancedSearch().TechnologyIds().push(technology.Id);
        self.generateRoute();
    };
    //SET COMPANYID
    self.companyId = ko.observable(0);
    self.setCompanyId = function(position) {
        self.positionAdvancedSearch().CompanyProfileIds().push(position.CompanyProfileId());
        self.generateRoute();
    };
    //SET PositionID AND MODE
    self.positionId = ko.observable(0);
    self.mode = ko.observable("");

    //LIST AND MYLIST
    self.setListRoute = function() {
        self.resetSearchModel();
        self.positionAdvancedSearch().UserId(0);
        self.positionViewMode("list");
        self.generateRoute();
    };
    self.setMyListRoute = function() {
        self.resetSearchModel();
        self.positionAdvancedSearch().UserId(1);
        self.positionViewMode("myList");
        self.loadPositionsAdvancedSearchAll();
    };
    self.userSignedIn = ko.observable(false);
    self.signedIn = function() {
        $.ajax({
                url: "/Position/CheckSignedIn",
                type: 'post',
                data: { positionId: self.workingPosition().Id() },
                success: function(result) {
                    self.userSignedIn(result);
                }
            });
    };
    //set profile as default
    self.setAsDefault = function(position) {
        $.ajax({
                url: "/Position/SetAsDefault",
                type: 'post',
                data: ko.toJSON(position),
                contentType: 'application/json',
                success: function() {
                    self.setMyListRoute();
                    parent.profile.setMyListRoute();
                    parent.company.setMyListRoute();
                }
            });
    };
    self.editDeleteNewButton = ko.observable(false);
    self.messageButton = ko.observable(true);
    self.editDeleteNewButtonsVisible = ko.computed(function() {
        var mode = self.positionViewMode();
        //check if user is signed in
        if (mode == "details") {
            self.signedIn();
        }
        if (mode == "myList" || self.userSignedIn() == true) {
            self.editDeleteNewButton(true);
            self.messageButton(false);
        } else {
            self.editDeleteNewButton(false);
            self.messageButton(true);
        }
    });


    self.setDefaultSidebarIds = function() {
        self.selectedCountryId(-1);
    };

    //RESET SEARCH MODEL
    self.resetSearchModel = function() {
        self.workingPositionId(null);
        self.positionViewMode("list");
        self.positionAdvancedSearch().PageIndex(parent.pageIndexDefault);
        self.positionAdvancedSearch().PageSize(parent.pageSizeDefault);
        self.positionAdvancedSearch().CountryIds([]);
        self.positionAdvancedSearch().CategoryIds([]);
        self.positionAdvancedSearch().TechnologyIds([]);
        self.positionAdvancedSearch().CompanyProfileIds([]);
    };

    self.generateRoute = function() {
        var pageIndex = self.positionAdvancedSearch().PageIndex();
        var pageSize = self.positionAdvancedSearch().PageSize();
        var countryId = self.positionAdvancedSearch().CountryIds()[0];
        var categoryId = self.positionAdvancedSearch().CategoryIds()[0];
        var technologyId = self.positionAdvancedSearch().TechnologyIds()[0];
        var companyId = self.positionAdvancedSearch().CompanyProfileIds()[0];
        var id = self.workingPositionId();
        var mode = self.positionViewMode();
        var route = '#/Positions/?';
        var defaultRoute = route;
        if (id != null) {
            route = route + (defaultRoute != route ? '&' : '') + 'id=' + id;
        }
        if (mode != null && mode != "" && mode != "advancedSearch") {
            route = route + (defaultRoute != route ? '&' : '') + 'mode=' + mode;
        }
        if (pageIndex != null && pageIndex != parent.pageIndexDefault && (mode == "list" || mode == "myList")) {
            route = route + (defaultRoute != route ? '&' : '') + 'pageIndex=' + pageIndex;
        }
        if (pageSize != null && pageSize != parent.pageSizeDefault && (mode == "list" || mode == "myList")) {
            route = route + (defaultRoute != route ? '&' : '') + 'pageSize=' + pageSize;
        }
        if (self.positionAdvancedSearch().CountryIds().length != 0 && self.positionAdvancedSearch().CountryIds()[0] != -1 && mode != "advancedSearch") {
            route = route + (defaultRoute != route ? '&' : '') + 'countryId=' + countryId;
        }
        if (self.positionAdvancedSearch().CategoryIds().length != 0 && mode != "advancedSearch") {
            route = route + (defaultRoute != route ? '&' : '') + 'categoryId=' + categoryId;
        }
        if (self.positionAdvancedSearch().TechnologyIds().length != 0 && mode != "advancedSearch") {
            route = route + (defaultRoute != route ? '&' : '') + 'technologyId=' + technologyId;
        }
        if (self.positionAdvancedSearch().CompanyProfileIds().length != 0) {
            route = route + (defaultRoute != route ? '&' : '') + 'companyId=' + companyId;
        }
        location.hash = route;
    };


    self.loadPositionsAdvancedSearchAll = function() {
        self.noResultsMessageVisible(false);
        if (self.positionViewMode() == "list" || self.positionViewMode() == "myList") {
            $.ajax({
                    url: "/Position/ListAdvancedSearchAll",
                    type: 'post',
                    data: ko.toJSON(self.positionAdvancedSearch()),
                    contentType: "application/json",
                    success: function(allData) {
                        self.pagesCount(allData.PagesCount);
                        self.count(allData.Count);
                        var mappedPositions = $.map(allData.Entities, function(item) { return new Position(item); });
                        self.positions(mappedPositions);
                    }
                });
        }
    };
    
    self.showAllMyPositions = function () {
        self.positionAdvancedSearch().ShowAll(true);
        self.loadPositionsAdvancedSearchAll();
    };
    self.showLessMyPositions = function () {
        self.positionAdvancedSearch().ShowAll(false);
        self.loadPositionsAdvancedSearchAll();
    };
    
    self.loadPositionsAdvancedSearchSome = function() {
        self.noResultsMessageVisible(false);
        $.ajax({
                url: "/Position/ListAdvancedSearchSome",
                type: 'post',
                data: ko.toJSON(self.positionAdvancedSearch()),
                contentType: "application/json",
                success: function(allData) {
                    self.pagesCountPositions(allData.PagesCount);
                    self.countPositions(allData.Count);
                    var mappedPositions = $.map(allData.Entities, function(item) { return new Position(item); });
                    self.Positions(mappedPositions);
                    //self.PositionAdvancedSearch(new PositionAdvancedSearch({ }));
                    //self.searchTypePositions("all");
                }
            });
    };

    self.noResultsMessageVisible = ko.observable(false);
    self.search = function() {
        self.noResultsMessageVisible(false);
        if (self.positionAdvancedSearch().CountryIds().length == 1) {
            self.selectedCountryId(self.positionAdvancedSearch().CountryIds()[0]);
        } else {
            self.selectedCountryId(-1);
        }
        if (self.positionAdvancedSearch().IndustryIds().length == 1) {
            self.selectedIndustryId(self.positionAdvancedSearch().IndustryIds()[0]);
        } else {
            self.selectedIndustryId(-1);
        }
        if (self.positionAdvancedSearch().JobTypes().length == 1) {
            self.selectedJobType(self.positionAdvancedSearch().JobTypes()[0]);
        } else {
            self.selectedJobType(-1);
        }
        $.ajax({
                url: "/Position/ListAdvancedSearchAll",
                type: 'post',
                data: ko.toJSON(self.positionAdvancedSearch()),
                contentType: "application/json",
                success: function(allData) {
                    self.pagesCount(allData.PagesCount);
                    self.count(allData.Count);
                    var mappedPositions = $.map(allData.Entities, function(item) { return new Position(item); });
                    self.Positions(mappedPositions);
                    if (self.Positions().length == 0) {
                        self.positionViewMode("list");
                        self.tableOfPositionsVisible(false);
                        self.noResultsMessageVisible(true);
                    } else {
                        self.tableOfPositionsVisible(true);
                        self.noResultsMessageVisible(false);
                        self.generateRoute();
                    }
                }
            });
    };
    self.resetSimpleSearch = function() {
        self.selectedCountryId(-1);
        self.selectedIndustryId(-1);
        self.selectedJobType(-1);
        self.positionAdvancedSearch(new PositionAdvancedSearch({ }));
        self.loadPositionsAdvancedSearchAll();
    };

    self.availableCountries = ko.observableArray([]);
    self.loadCountries = function() {
        $.getJSON("/ExpertProfile/GetJsonCountry", function(countries) {
            self.availableCountries(countries);
        });
    };


    //GMAP
    self.gmapLocationAutocomplete = function() {
        $.when(loadGoogleMaps(3, null, null))
            .then(function() {
                $.cachedScript("../../Scripts/gmap3/gmap3.min.js").done(function() {
                    $('#locationAutocompletePosition').autocompleteG({
                            source: function() {
                                $("#locationPosition").gmap3({
                                        action: 'getAddress',
                                        address: $(this).val() + ', ' + self.workingPosition().Country().Description,
                                        callback: function(results) {
                                            if (!results) return;
                                            $('#locationAutocompletePosition').autocompleteG('display', results, false);
                                            // add value from autocomplete so Location can be valid and modal can be closed
                                            //self.workingPositionBuffer().Location($('#locationAutocompletePosition').val());
                                        }
                                    });
                                $("#locationPositionViewMode").gmap3({
                                        action: 'getAddress',
                                        address: $(this).val() + ', ' + self.workingPosition().Country().Description,
                                        callback: function(results) {
                                            if (!results) return;
                                            $('#locationAutocompletePosition').autocompleteG('display', results, false);
                                        }
                                    });
                                $("#locationPositionEditMode").gmap3({
                                        action: 'getAddress',
                                        address: $(this).val() + ', ' + self.workingPosition().Country().Description,
                                        callback: function(results) {
                                            if (!results) return;
                                            $('#locationAutocompletePosition').autocompleteG('display', results, false);
                                        }
                                    });
                            },
                            cb: {
                                cast: function(item) {
                                    return item.formatted_address;
                                },
                                select: function(item) {
                                    $("#locationPosition").gmap3(
                                        { action: 'clear', name: 'marker' },
                                        { action: 'addMarker', latLng: item.geometry.location },
                                        { action: 'setCenter', args: [item.geometry.location] },
                                        { action: 'clear', name: 'InfoWindow' },
                                        {
                                            action: 'addInfoWindow',
                                            address: $(this).val(),
                                            map: {
                                                center: true,
                                                zoom: 10
                                            },
                                            infowindow: {
                                                options: { content: $(this).val() }
                                            }
                                        });
                                    $("#locationPositionViewMode").gmap3(
                                        { action: 'clear', name: 'marker' },
                                        { action: 'addMarker', latLng: item.geometry.location },
                                        { action: 'setCenter', args: [item.geometry.location] });
                                    $("#locationPositionEditMode").gmap3(
                                        { action: 'clear', name: 'marker' },
                                        { action: 'addMarker', latLng: item.geometry.location },
                                        { action: 'setCenter', args: [item.geometry.location] });
                                }
                            }
                        });
                });
            });
    };


    self.gmapLocationEditMode = function() {
        $.when(loadGoogleMaps(3, null, null))
            .then(function() {
                $.cachedScript("../../Scripts/gmap3/gmap3.min.js").done(function() {
                    var loc = self.workingPosition() ? self.workingPosition().Location() ? self.workingPosition().Location() : "" : "";
                    $("#locationPositionEditMode").gmap3({
                            action: 'getAddress',
                            address: loc,
                            callback: function(results) {
                                if (!results) return;
                                $("#locationPositionEditMode").gmap3(
                                    { action: 'clear', name: 'marker' },
                                    { action: 'addMarker', latLng: results[0].geometry.location },
                                    { action: 'setCenter', args: [results[0].geometry.location] }
                );
                            }
                        });
                });
            });
    };

    //TECHNOLOGIES
    self.availableTechnologiesNames = ko.observable([]);
    self.newTechnology = ko.observable();
    self.loadTechnologies = function() {
        $.getJSON("/Position/GetJsonTechnologies", function(technologies) {
            self.availableTechnologiesNames(technologies);
        });
    };
    self.autocompleteTechnologiesEdit = function() {
        $("#technologiesEditPositionAutocomplete").autocomplete({
                source: function(request, response) {
                    $.ajax({
                            url: "Technology/GetTechnologiesAutocomplete",
                            dataType: "json",
                            data: {
                                searchTerm: request.term,
                                maxRows: 8
                            },
                            success: function(data) {
                                response($.map(data, function(item) {
                                    return {
                                        label: item.Name,
                                        value: item.Id
                                    };
                                }));
                            }
                        });
                },
                minLength: 2,
                select: function(event, ui) {
                    var id = ui.item.value;
                    var description = ui.item.label;

                    self.technologyTags.push({ Id: id, Description: description });
                    self.positionAdvancedSearch().TechnologyIds.push(id);
                    $("#technologiesEditPositionAutocomplete").val(description);
                    return false;
                }
            });
    };


    //AUTOCOMPLETE
    self.autocompleteCategories = function() {
        $("#categoriesPositionsAutocomplete").autocomplete({
                source: function(request, response) {
                    $.ajax({
                            url: "Category/GetCategoriesAutocomplete",
                            dataType: "json",
                            data: {
                                searchTerm: request.term,
                                maxRows: 8
                            },
                            success: function(data) {
                                response($.map(data, function(item) {
                                    return {
                                        label: item.Description,
                                        value: item.Id
                                    };
                                }));
                            }
                        });
                },
                minLength: 0,
                select: function(event, ui) {
                    var id = ui.item.value;
                    var description = ui.item.label;

                    var found = ko.utils.arrayFirst(self.categoryTags(), function(item) {
                        return item.Description == description;
                    });
                    if (!found) {
                        self.categoryTags.push({ Id: id, Description: description });
                        self.positionAdvancedSearch().CategoryIds.push(id);
                    }

                    $("#categoriesPositionsAutocomplete").val("");
                    return false;
                },
                focus: function(event, ui) {
                    this.value = ui.item.label;
                    event.preventDefault(); // Prevent the default focus behavior.
                }
            });
    };
    self.showAllCategories = function() {
        $("#categoriesPositionsAutocomplete").autocomplete("search", "");
        $("#categoriesPositionsAutocomplete").focus();
    };
    self.removeCategoryTag = function(tag) {
        self.categoryTags.remove(tag);
        self.positionAdvancedSearch().CategoryIds.remove(function(item) { return item == tag.Id; });
    };

    self.autocompleteTechnologies = function() {
        $("#technologiesPositionsAutocomplete").autocomplete({
                source: function(request, response) {
                    $.ajax({
                            url: "Technology/GetTechnologiesAutocomplete",
                            dataType: "json",
                            data: {
                                searchTerm: request.term,
                                maxRows: 8
                            },
                            success: function(data) {
                                response($.map(data, function(item) {
                                    return {
                                        label: item.Name,
                                        value: item.Id
                                    };
                                }));
                            }
                        });
                },
                minLength: 0,
                select: function(event, ui) {
                    var id = ui.item.value;
                    var description = ui.item.label;

                    var found = ko.utils.arrayFirst(self.technologyTags(), function(item) {
                        return item.Description == description;
                    });
                    if (!found) {
                        self.technologyTags.push({ Id: id, Description: description });
                        self.positionAdvancedSearch().TechnologyIds.push(id);
                    }

                    $("#technologiesPositionsAutocomplete").val("");
                    return false;
                },
                focus: function(event, ui) {
                    this.value = ui.item.label;
                    event.preventDefault(); // Prevent the default focus behavior.
                }
            });
    };
    self.showAllTechnologies = function() {
        $("#technologiesPositionsAutocomplete").autocomplete("search", "");
        $("#technologiesPositionsAutocomplete").focus();
    };
    self.removeTechnologyTag = function(tag) {
        self.technologyTags.remove(tag);
        self.positionAdvancedSearch().TechnologyIds.remove(function(item) { return item == tag.Id; });
    };
    self.autocompleteCountries = function() {
        $("#countriesPositionsAutocomplete").autocomplete({
                source: function(request, response) {
                    $.ajax({
                            url: "Country/GetCountriesAutocomplete",
                            dataType: "json",
                            data: {
                                searchTerm: request.term,
                                maxRows: 8
                            },
                            success: function(data) {
                                response($.map(data, function(item) {
                                    return {
                                        label: item.Description,
                                        value: item.Id
                                    };
                                }));
                            }
                        });
                },
                minLength: 0,
                select: function(event, ui) {
                    var id = ui.item.value;
                    var description = ui.item.label;

                    var found = ko.utils.arrayFirst(self.countryTags(), function(item) {
                        return item.Description == description;
                    });
                    if (!found) {
                        self.countryTags.push({ Id: id, Description: description });
                        self.positionAdvancedSearch().CountryIds.push(id);
                    }

                    $("#countriesPositionsAutocomplete").val("");
                    return false;
                },
                focus: function(event, ui) {
                    this.value = ui.item.label;
                    event.preventDefault(); // Prevent the default focus behavior.
                }
            });
    };
    self.showAllCountries = function() {
        $("#countriesPositionsAutocomplete").autocomplete("search", "");
        $("#countriesPositionsAutocomplete").focus();
    };
    self.removeCountryTag = function(tag) {
        self.countryTags.remove(tag);
        self.positionAdvancedSearch().CountryIds.remove(function(item) { return item == tag.Id; });
    };

    self.autocompleteCompanies = function() {
        $("#companiesPositionsAutocomplete").autocomplete({
                source: function(request, response) {
                    $.ajax({
                            url: "CompanyProfile/GetCompaniesAutocomplete",
                            dataType: "json",
                            data: {
                                searchTerm: request.term,
                                maxRows: 8
                            },
                            success: function(data) {
                                response($.map(data, function(item) {
                                    return {
                                        label: item.Title,
                                        value: item.Id
                                    };
                                }));
                            }
                        });
                },
                minLength: 0,
                select: function(event, ui) {
                    var id = ui.item.value;
                    var description = ui.item.label;

                    var found = ko.utils.arrayFirst(self.companyTags(), function(item) {
                        return item.Description == description;
                    });
                    if (!found) {
                        self.companyTags.push({ Id: id, Description: description });
                        self.positionAdvancedSearch().CompanyProfileIds.push(id);
                    }

                    $("#companiesPositionsAutocomplete").val("");
                    return false;
                },
                focus: function(event, ui) {
                    this.value = ui.item.label;
                    event.preventDefault(); // Prevent the default focus behavior.
                }
            });
    };
    self.showAllCompanies = function() {
        $("#companiesPositionsAutocomplete").autocomplete("search", "");
        $("#companiesPositionsAutocomplete").focus();
    };
    self.removeCompanyTag = function(tag) {
        self.companyTags.remove(tag);
        self.positionAdvancedSearch().CompanyProfileIds.remove(function(item) { return item == tag.Id; });
    };

    self.autocompleteIndustries = function() {
        $("#industriesPositionsAutocomplete").autocomplete({
                source: function(request, response) {
                    $.ajax({
                            url: "Industry/GetIndustriesAutocomplete",
                            dataType: "json",
                            data: {
                                searchTerm: request.term,
                                maxRows: 8
                            },
                            success: function(data) {
                                response($.map(data, function(item) {
                                    return {
                                        label: item.Description,
                                        value: item.Id
                                    };
                                }));
                            }
                        });
                },
                minLength: 0,
                select: function(event, ui) {
                    var id = ui.item.value;
                    var description = ui.item.label;

                    var found = ko.utils.arrayFirst(self.industryTags(), function(item) {
                        return item.Description == description;
                    });
                    if (!found) {
                        self.industryTags.push({ Id: id, Description: description });
                        self.positionAdvancedSearch().IndustryIds.push(id);
                    }

                    $("#industriesPositionsAutocomplete").val("");
                    return false;
                },
                focus: function(event, ui) {
                    this.value = ui.item.label;
                    event.preventDefault(); // Prevent the default focus behavior.
                }
            });
    };
    self.showAllIndustries = function() {
        $("#industriesPositionsAutocomplete").autocomplete("search", "");
        $("#industriesPositionsAutocomplete").focus();
    };
    self.removeIndustryTag = function(tag) {
        self.industryTags.remove(tag);
        self.positionAdvancedSearch().IndustryIds.remove(function(item) { return item == tag.Id; });
    };

    self.autocompleteEmploymentTypes = function() {
        $("#employmentTypesPositionsAutocomplete").autocomplete({
                source: function(request, response) {
                    $.ajax({
                            url: "ExpertProfile/GetJobTypesAutocomplete",
                            dataType: "json",
                            data: {
                                searchTerm: request.term,
                                maxRows: 8
                            },
                            success: function(data) {
                                response($.map(data, function(item) {
                                    return {
                                        label: item.Description,
                                        value: item.Value
                                    };
                                }));
                            }
                        });
                },
                minLength: 0,
                select: function(event, ui) {
                    var value = ui.item.value;
                    var description = ui.item.label;

                    var found = ko.utils.arrayFirst(self.employmentTypeTags(), function(item) {
                        return item.Description == description;
                    });
                    if (!found) {
                        self.employmentTypeTags.push({ Value: value, Description: description });
                        self.positionAdvancedSearch().JobTypes.push(value);
                    }

                    $("#employmentTypesPositionsAutocomplete").val("");
                    return false;
                },
                focus: function(event, ui) {
                    this.value = ui.item.label;
                    event.preventDefault(); // Prevent the default focus behavior.
                }
            });
    };
    self.showAllEmploymentTypes = function() {
        $("#employmentTypesPositionsAutocomplete").autocomplete("search", "");
        $("#employmentTypesPositionsAutocomplete").focus();
    };
    self.removeEmploymentTypeTag = function(tag) {
        self.employmentTypeTags.remove(tag);
        self.positionAdvancedSearch().ContractTypes.remove(function(item) { return item == tag.Value; });
    };

    self.autocompleteKeywords = function() {
        $("#keywordsPositionsAutocomplete").autocomplete({
                source: function(request, response) {
                    $.ajax({
                            url: "Position/GetKeywordsAutocomplete",
                            dataType: "json",
                            data: {
                                searchTerm: request.term,
                                maxRows: 8
                            },
                            success: function(data) {
                                response($.map(data, function(item) {
                                    return {
                                        label: item.Description,
                                        value: item.Type + item.Id
                                    };
                                }));
                            }
                        });
                },
                minLength: 0,
                select: function(event, ui) {
                    var description = ui.item.label;
                    var type = ui.item.value.substring(0, 2);
                    var id = ui.item.value.substring(2);
                    //"la" as in "lands"
                    if (type == "la") {
                        self.countryTags.push({ Id: id, Description: description });
                        self.positionAdvancedSearch().CountryIds.push(id);
                    } else if (type == "in") {
                        self.industryTags.push({ Id: id, Description: description });
                        self.positionAdvancedSearch().IndustryIds.push(id);
                    } else if (type == "ca") {
                        self.categoryTags.push({ Id: id, Description: description });
                        self.positionAdvancedSearch().CategoryIds.push(id);
                    } else if (type == "te") {
                        self.technologyTags.push({ Id: id, Description: description });
                        self.positionAdvancedSearch().TechnologyIds.push(id);
                    } else if (type == "co") {
                        self.companyTags.push({ Id: id, Description: description });
                        self.positionAdvancedSearch().CompanyProfileIds.push(id);
                    }
                    if (event.keyCode == 13) {
                        self.enterKeyPressed = true;
                    }
                    $("#keywordsPositionsAutocomplete").val("");
                    return false;
                },
                focus: function(event, ui) {
                    this.value = ui.item.label;
                    event.preventDefault(); // Prevent the default focus behavior.
                }
            });
    };
    self.addKeywordTag = function() {
        self.keywordTags.push({ Description: self.keyword() });
        self.positionAdvancedSearch().Keywords.push(self.keyword());
        var tag = $.Enumerable.From(self.keywordTags()).SingleOrDefault(null, function(x) {
            return self.keyword() === x.Description;
        });
        //if enter key is not pressed while selection => remove tag from keywordTags
        if (self.enterKeyPressed) {
            self.keywordTags.remove(tag);
            self.positionAdvancedSearch().Keywords.remove(function(item) { return item == self.keyword(); });
        }
        self.enterKeyPressed = false;
        $("#keywordsPositionsAutocomplete").val("");
        return false;
    };
    self.removeKeywordTag = function(tag) {
        self.keywordTags.remove(tag);
        self.positionAdvancedSearch().Keywords.remove(function(item) { return item == tag.Description; });
    };

    //UPLOAD PHOTO
    self.photo = ko.observable("");
    self.beforePhotoUpload = ko.observable(true);
    self.afterPhotoUpload = ko.observable(false);
    self.uploadPhotoProgressBarVisible = ko.observable(false);
    self.resetPhotoUpload = function() {
        self.beforePhotoUpload(true);
        self.afterPhotoUpload(false);
        self.photoAlertVisible(false);
        self.uploadPhotoProgressBarVisible(false);
        $('#dropZonePhotoPosition').css('background', 'lightgray');
    };
    self.photoAlertVisible = ko.observable(false);
    self.dropPhoto = function() {
        $('#dropZonePhotoPosition').filedrop({
                url: 'Upload/UploadPositionPhoto',
                paramname: 'file',
                maxFiles: 1,
                maxfilesize: 5,
                data: { PositionId: self.workingPosition().Id() },
            //allowedfiletypes: ['image/jpg', 'image/png', 'image/gif'],
                dragOver: function() {
                    $('#dropZonePositionPhoto').css('background', 'white');
                },
                dragLeave: function() {
                    $('#dropZonePositionPhoto').css('background', 'gray');
                },
                drop: function() {
                    $('#dropZonePositionPhoto').css('background', 'gray');
                },
                progressUpdated: function(i, file, progress) {
                    // this function is used for large files and updates intermittently
                    // progress is the integer value of file being uploaded percentage to completion
                    self.uploadPhotoProgressBarVisible(true);
                    $("#uploadPhotoPositionProgressBar").width(progress + "%");
                    $("#uploadPhotoPositionProgressBar").width(100 + "%");
                },
                uploadFinished: function(i, file, response, time) {
                    self.workingPositionBuffer().Photo(response);
                    if (self.workingPositionBuffer().Photo.isValid()) {
                        $('#uploadPositionPhotoResult').html('');
                        $('#uploadPositionPhotoResult').html(file.name);
                        self.photo(response);
                        self.beforePhotoUpload(false);
                        self.afterPhotoUpload(true);
                    } else {
                        self.photoAlertVisible(true);
                    }
                }
            });
    };
}